from sqlalchemy.ext.asyncio import AsyncSession as Session
from app.models.xm.xm_archive import XmArchive
from app.schemas.xm.xm_archive import XmArchiveCreate
from typing import Optional
from sqlalchemy import select

async def create_archive(session: Session, archive: XmArchiveCreate) -> XmArchive:
    db_archive = XmArchive(**archive.model_dump())
    session.add(db_archive)
    await session.commit()
    await session.refresh(db_archive)
    return db_archive

async def get_archive(session: Session, archiveId: int) -> Optional[XmArchive]:
    db_xm_archive = await session.execute(
        select(XmArchive).where(XmArchive.archiveId == archiveId)
    )
    return db_xm_archive.scalar_one_or_none()

async def get_archive_page(
    session: Session,
    pageNo: int = 1,
    pageSize: int = 100,
) -> list[XmArchive]:
    """查询XM档案列表"""
    statement = select(XmArchive)
    # 计算总数
    total = await session.execute(statement)
    total = len(total.scalars().all())
    # 分页查询
    statement = statement.offset((pageNo - 1) * pageSize).limit(pageSize)
    result = await session.execute(statement)
    return {
        "records": result.scalars().all(),
        "total": total,
        "pageNo": pageNo,
        "pageSize": pageSize
    }
